// 管理员初始化
// 判断数据库中是否有管理员，如果没有，自动添加一个默认管理员
const Admin = require("../models/Admin");
const { Op } = require("sequelize");
const {
  filterProperty,
  pickerProperty,
  deepClone,
} = require("../utils/operateProperty");
const md5 = require("md5");
const validate = require("validate.js");
// 添加修改管理员验证规则模板
const rule = {
  name: {
    presence: {
      // 不允许为空
      allowEmpty: false,
    },
    type: "string", // 类型为字符串
    length: { minimum: 1, maximum: 10 }, // 长度在1到10之间
  },
  account: {
    presence: {
      allowEmpty: false,
    },
    type: "string", // 类型为字符串
    length: { minimum: 5 }, // 长度在不少于5位
  },
  password: {
    presence: {
      allowEmpty: false,
    },
    type: "string",
    length: { minimum: 5, maximum: 20 },
  },
};
class AdminService {
  constructor() {
    this.init();
  }
  init() {
    Admin.findAll().then((admins) => {
      if (admins.length === 0) {
        this.addAdmin({
          name: "admin",
          account: "admin",
          password: "admin",
        });
      }
    });
  }
  // 添加管理员
  addAdmin(adminObj) {
    // 数据筛选
    adminObj = pickerProperty(adminObj, Object.keys(rule));
    // 添加数据库验证
    return this.validatorAdminObj(adminObj, async function (value) {
      return Admin.findOne({ where: { account: value } }).then((res) => {
        if (res) {
          return "is exist";
        }
      });
    })
      .then(() => {
        // 密码进行md5加密
        adminObj["password"] = md5(adminObj["password"]);
        // 判断数据库中是否有管理员，如果没有，自动添加一个默认管理员
        return Admin.create(adminObj);
      })
      .then(() => {
        console.log("添加管理员成功");
      });
  }
  // 更新管理员
  updateAdmin(id, adminObj) {
    // 数据筛选
    adminObj = pickerProperty(adminObj, Object.keys(rule));
    // 验证id格式
    const res = this.validatorId(id);
    if (res)
      return Promise.reject(["id can't be blank and must be of type integer"]);
    // 验证修改数据数据库中是否存在并且格式正确
    return this.validatorAdminObj(adminObj, async function (value) {
      const admin = await Admin.findOne({
        where: {
          [Op.and]: [{ id: id }, { account: value }],
        },
      });
      if (!admin) {
        return "is not exist, cannot update this account";
      }
    })
      .then(() => {
        // 密码进行md5加密
        adminObj["password"] = md5(adminObj["password"]);
        return Admin.update(adminObj, {
          where: {
            id: id,
          },
        });
      })
      .then(() => {
        console.log("更新成功");
      });
  }
  // 删除管理员
  deleteAdmin(adminId) {
    // 验证id格式
    const res = this.validatorId(id);
    if (res)
      return Promise.reject(["id can't be blank and must be of type integer"]);
    return Admin.destroy({
      where: {
        id: adminId,
      },
    }).then(() => {
      console.log("删除成功");
    });
  }

  // 查询管理员
  // 根据id获取管理员
  getAdminById(id) {
    // 验证id格式
    const res = this.validatorId(id);
    if (res)
      return Promise.reject(["id can't be blank and must be of type integer"]);
    // 1. findByPk (推荐)
    return Admin.findByPk(id).then((admin) => {
      if (!admin) {
        return Promise.reject(["admin is not exist"]);
      }
      // console.log('admin', admin)
      return filterProperty(
        admin.dataValues,
        ["password", "deletedAt"],
        "createdAt",
        "updatedAt"
      );
    });
    // 2. findOne
    /* return Admin.findOne({
      where: {
        id,
      },
    }).then((admin) => {
      // console.log('admin', admin)
      return filterProperty(
        admin.dataValues,
        ["password", "deletedAt"],
        "createdAt",
        "updatedAt"
      );
    }); */
    // 3.findAll
    /* return Admin.findAll({
      where: {
        id,
      },
    }).then((admins) => {
      return filterProperty(
        admins[0].dataValues,
        ["password", "deletedAt"],
        "createdAt",
        "updatedAt"
      );
    }); */
  }

  getAdmins() {
    return Admin.findAll().then((admins) => {
      return admins.map((admin) => {
        return filterProperty(
          admin.dataValues,
          ["password", "deletedAt"],
          "createdAt",
          "updatedAt"
        );
      });
    });
  }

  async login(account, password) {
    // 密码进行md5加密方便比对数据库数据
    password = md5(password);
    const admin = await Admin.findOne({
      attributes: ["id", "account"],
      where: {
        account,
      },
    });
    // console.log("admin", admin)
    if (admin) {
      return admin;
    } else {
      return null;
    }
  }

  validatorId(id) {
    return validate.single(id, {
      presence: { allowEmpty: false },
      type: "integer",
    });
  }
  validatorAdminObj(adminObj, validator) {
    const rules = deepClone(rule);
    rules.account.exist = {
      validator,
    };
    // 验证修改数据数据库中是否存在并且格式正确
    return validate.async(adminObj, rules);
  }
}

const adminService = new AdminService();
module.exports = adminService;
